import asyncio
import time
from core.logger import log
# from services.redis_service import AsyncRedisService
from services.wx_chat_messages import create_wx_messages
from utils.baidu_ocr_api import baidu_ocr_table, analysis_ocr_reply, baidu_ocr_table as baidu_ocr_table_by_url
from utils.socket_util import broadcast_message
from utils.rag_api import get_reply_by_rag
from utils.sender_tools import SenderTools


class MsgAsyncScheduler:

    def __init__(self,monitoring_tasks,monitoring_states,sio,redis_service):
        self.sender_tools = SenderTools()
        self.server = redis_service
        self.monitoring_tasks = monitoring_tasks
        self.monitoring_states = monitoring_states
        self.sio = sio


    async def process_list_data(self, from_user: str, to_user: str, data_type: str,key: str=None,next_content: str = None):
        """
        处理Redis列表中的所有数据
        """
        try:
            content = []
            if data_type == "base64":
                # 获取列表中的所有数据
                list_data = await self.server.get_base64_list(from_user,to_user)
                log.info(f"处理 {from_user}:{to_user} 的数据，共 {len(list_data)} 条")
                for i, base64_data in enumerate(list_data):
                    # 这里可以调用OCR或其他处理函数
                    content_result = await baidu_ocr_table(base64_data=base64_data)
                    content = content + content_result
            elif data_type == "image_url":
                list_data = await self.server.get_image_urls_list(from_user,to_user)
                log.info(f"处理 {from_user}:{to_user} 的数据，共 {len(list_data)} 条")
                for i, url in enumerate(list_data):
                    # 这里可以调用OCR或其他处理函数
                    content_result = await baidu_ocr_table_by_url(image_url=url)
                    content = content + content_result
            else:
                log.info(f"{data_type} 错误类型")
                content = None
                # 确保 content 不为空再继续处理
            if not content:
                log.warning(f"处理 {from_user}:{to_user} 时未获取到任何内容")
                return
            result = await analysis_ocr_reply(content)

            res = f"类型: 图片, 图片OCR识别后的文本: {result}"
            log.info(f"OCR结果{res}")
            if next_content:
                res = res+" "+next_content
                if key:
                    await create_wx_messages(from_user, to_user, "接收", next_content)
            reply = await get_reply_by_rag(res, from_user, to_user)
            if "##" in reply:
                return
            if not key:
                await create_wx_messages(to_user, from_user, "接收", reply)
            else:
                send = self.sender_tools.send_wx_message(reply, from_user, key)
                log.info(f"发送结果: {send}")
                await create_wx_messages(to_user, from_user, "回复", reply)
            await broadcast_message(sio=self.sio,message_data={"content": reply, "device_id": from_user, "wx_id": to_user},room=to_user)
        except Exception as e:
            log.error(f"处理 {from_user}:{to_user} 数据时出错: {e}")

    async def start_monitoring_task(self, from_user: str, to_user: str, data_type: str,key:str=None):
        """
        启动监控任务
        """
        task_key = f"{from_user}:{to_user}"
        # 确保Redis连接

        # 如果已经有相同的监控任务在运行，则不重复启动
        if task_key in self.monitoring_tasks and not self.monitoring_tasks[task_key].done():
            log.info(f"监控任务 {task_key} 已经在运行中")
            return

        # 创建并启动新的监控任务
        task = asyncio.create_task(self.monitor_redis_list(from_user, to_user, data_type=data_type,key=key))
        self.monitoring_tasks[task_key] = task
        self.monitoring_states[task_key] = {
            "last_length": 0,
            "last_change_time": time.time()
        }

        log.info(f"启动监控任务: {task_key}")

    async def monitor_redis_list(self, from_user: str, to_user: str, data_type: str,key:str= None):
        """
        监控Redis列表长度变化的定时任务
        """
        task_key = f"{from_user}:{to_user}"
        if data_type == "base64":
            list_key = f"base64:{from_user}:{to_user}"
        elif data_type == "image_url":
            list_key = f"image_url:{from_user}:{to_user}"
        else:
            return

        try:


            while True:
                try:
                    # 获取列表当前长度
                    current_length = await self.server.redis_service.llen(list_key)
                    state = self.monitoring_states[task_key]
                    log.info(f"检查 {task_key} 列表长度: {current_length}, 上次长度: {state['last_length']}")
                    if current_length != state["last_length"]:
                        # 长度发生变化，更新状态
                        state["last_length"] = current_length
                        state["last_change_time"] = time.time()
                        log.info(f"{task_key} 列表长度已更新为 {current_length}")
                    else:
                        # 长度未变化，检查是否超过1分钟
                        time_since_last_change = time.time() - state["last_change_time"]
                        if time_since_last_change >= 60:  # 1分钟
                            log.info(f"{task_key} 1分钟内无变化，开始处理数据")
                            # 处理列表中的所有数据
                            await self.process_list_data(from_user, to_user, data_type=data_type,key=key)
                            # 处理完成后退出监控循环
                            break

                    # 每5秒检查一次
                    await asyncio.sleep(5)

                except Exception as e:
                    log.error(f"监控任务 {task_key} 检查过程中出错: {e}")
                    break

        except Exception as e:
            log.error(f"监控任务 {task_key} 初始化失败: {e}")
        finally:
            # 清理任务记录
            if task_key in self.monitoring_tasks:
                del self.monitoring_tasks[task_key]
            if task_key in self.monitoring_states:
                del self.monitoring_states[task_key]
            log.info(f"监控任务 {task_key} 已结束")

    async def stop_monitoring_task(self, from_user: str, to_user: str):
        """
        停止监控任务
        """
        task_key = f"{from_user}:{to_user}"
        if task_key in self.monitoring_tasks:
            task = self.monitoring_tasks[task_key]
            if not task.done():
                task.cancel()
                del self.monitoring_tasks[task_key]
                log.info(f"已停止监控任务: {task_key}")
            else:
                log.info(f"监控任务 {task_key} 已完成")